var app = getApp();
const util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navbar: ['最新参与', '点赞排行'],
    currentTab: 0,
    leftList: [],
    rightList: [],
    leftHight: 0,
    rightHight: 0,
    filled: false,
    signUpIng: 0,
    hasSigned: false,
    activityId: null,
    activityInfo: null,
    pageNum: 1,
    pageSize: 6,
    sw: ""
  },
  navbarTap: function (e) {
    this.setData({
      currentTab: e.currentTarget.dataset.idx
    })
    this.setData({
      pageNum: 1,
      leftList: [],
      rightList: [],
      leftHight: 0,
      rightHight: 0,
      isOver: false
    })
    this.getProductList();
  },
  gotoAdd: function () {
    wx.navigateTo({
      url: "../index/index"
    });
  },
  gotoRanking: function () {
    wx.navigateTo({
      url: "/pages/zpsc/phb/phb?activityId=" + this.data.activityId
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.setData({
      activityId: options.activityId
    })
    this.activeDetail(options.activityId);
    this.getProductList();
    
  },

  getProductList: function() {
    wx.showLoading({
      title: '加载中...',
    })
    var that = this;
    var orderType = 4;
    if(that.data.currentTab == 1){
      orderType = 2
    }
    wx.request({
      url:  app.globalData.activityHost + '/services/activityaction/listActivityProductionWx',
      data: {
        activityId: that.data.activityId,
        currentPage: that.data.pageNum,
        pageSize: that.data.pageSize,
        sw: that.data.sw,
        orderType: orderType
      },
      success: function (res) {
        console.log(res);
        if (res.data.result == "0") {
          var allData = res.data.obj.data;
          //定义两个临时的变量来记录左右两栏的高度，避免频繁调用setData方法
          // var that = this;
          // var allData = that.data.noramalData;
          //定义两个临时的变量来记录左右两栏的高度，避免频繁调用setData方法
          var leftH = that.data.leftHight;
          var rightH = that.data.rightHight;
          var leftData = [];
          var rightData = [];
          for (let i = 0; i < allData.length; i++) {
            var currentItemHeight = parseInt(Math.round(allData[i].coverHeight * 345 / allData[i].coverWidth));
            allData[i].coverHeight = currentItemHeight + "rpx";//因为xml文件中直接引用的该值作为高度，所以添加对应单位
            if (leftH == rightH || leftH < rightH) {//判断左右两侧当前的累计高度，来确定item应该放置在左边还是右边
              leftData.push(allData[i]);
              leftH += currentItemHeight;
            } else {
              rightData.push(allData[i]);
              rightH += currentItemHeight;
            }
          }
          wx.hideLoading();
          //更新左右两栏的数据以及累计高度
          that.setData({
            leftHight: leftH,
            rightHight: rightH,
            // leftList: leftData,
            // rightList: rightData
            leftList: [...that.data.leftList, ...leftData],
            rightList: [...that.data.rightList, ...rightData],
            pageNum: that.data.pageNum + 1
          })

        } else {
          console.log("请求活动详情接口异常");
          wx.hideLoading()
        }
      },
      fail: function () {
        console.log("获取活动详情出错！")
        wx.hideLoading()
      }
    })
  },

  onChange: function(e) {
    this.setData({
      sw: e.detail.value
    })
  },

  /**
   * 跳转到详情页
   */
  gotoDetail: function(e){
    console.log(e);
    var type = e.currentTarget.dataset.type;
    var activityId = e.currentTarget.dataset.id;
    var uid = wx.getStorageSync('cxid');
    var fid = app.globalData.fid;
    wx.navigateTo({
      url: '/pages/link/link?url=https://videoshequ3.chaoxing.com/miniprogram/play&type=' + type + "&activityId=" + activityId + "&uid=" + uid + "&fid=" + fid,
    })
  },

  /**
   * 搜索
   */
  onSearch: function() {
    console.log(1)
    this.setData({
      pageNum: 1,
      leftList: [],
      rightList: [],
      leftHight: 0,
      rightHight: 0,
      isOver: false
    })
    this.getProductList();
  },
  onClick: function() {
    this.onSearch()
  },
  scrolltolower: function() {
    this.getProductList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    this.getProductList()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    console.log(e);
    let url = util.getCurrentPageUrlWithArgs();
    if (url.indexOf('?') > -1) {
      url += '&fid=' + app.globalData.fid + '&fidEnc=' + app.globalData.fidEnc;
    } else {
      url += '?fid=' + app.globalData.fid + '&fidEnc=' + app.globalData.fidEnc;
    }
    if (e.from == "menu") {
      return {
        title: app.globalData.site.name,
        path: url
      }
    }else{
      console.log(e);
      var type = e.target.dataset.type;
      var activityId = e.target.dataset.id;
      var uid = wx.getStorageSync('cxid');
      //TODO 暂时不考虑用户登录问题
      var _url = '/pages/link/link?url=https://videoshequ3.chaoxing.com/miniprogram/play&type=' + type + "&activityId=" + activityId + "&uid=" + uid + '&fid=' + app.globalData.fid + '&fidEnc=' + app.globalData.fidEnc;
      return {
        title: app.globalData.site.name,
        path: _url
      }
    }
  },

  /**
   * 根据活动id获取活动详情
   */
  activeDetail: function(id){
    var that = this;
    wx.request({
      url: app.globalData.activityHost + '/services/activityaction/getactivitybyid',
      data: {
        id: id
      },
      success: function(res){
        console.log(res);
        if (res.data.result == "0") {
          that.setData({
            activityInfo: res.data.obj
          })
          var start = new Date(res.data.obj.startDate);
          var end = new Date(res.data.obj.endDate);
          var now = new Date();
          if (now - start < 0) {
            that.setData({
              signUpIng: 2
            })
          } else if (now - start > 0 && now - end < 0) {
            that.setData({
              signUpIng: 0
            })
          } else if (now - end > 0) {
            that.setData({
              signUpIng: 1
            })
          }
        } else {
          console.log("请求活动详情接口异常");
        }
      },
      fail: function(){
        console.log("获取活动详情出错！")
      }
    })
  },

  /**
   * 判断报名状态
   */
  checkStatus: function(){
    var that = this;
    var cxid = wx.getStorageSync('cxid');
    console.log("超星ID： " + cxid);
    // if (cxid && cxid > 0) {
      wx.request({
        url: app.globalData.activityHost + '/services/activityaction/hasJoinActivity',
        data: {
          activityId: that.data.activityId,
          fid: that.data.fid,
          uid: cxid
        },
        success: function (res) {
          console.log(res);
          if (res.data.result == "1") {
            if(that.data.activityInfo.uploadStatus == 1){
              wx.navigateTo({
                url: '/pages/zpsc/upload/upload?activityId=' + that.data.activityId + "&cover=https://huibenbook.chaoxing.com/activity" + that.data.activityInfo.activityCover,
              })
            }else{
              wx.showToast({
                title: '您已报名成功！',
                icon: 'none'
              })
            }
          } else if (res.data.result == "0") {
            that.checkPerson();
           
          }

        },
        fail: function () {
          console.log("请求活动是否报名接口异常");
        }
      })
    // }
  },

  /**
   * 检测报名人数是否已满
   */
  checkPerson: function () {
    var that = this;
    var info = this.data.activityInfo;
    if (info.personCurrent >= info.personTotal) {
      wx.showToast({
        title: '报名人数已满！',
        icon: 'none'
      })
    }else{
      // 报名
      // that.enroll();

      wx.navigateTo({
        url: '/pages/zpsc/itoapply/itoapply?activityId=' + that.data.activityId + '&checkUserIDCardStatus=' + that.data.activityInfo.checkUserIDCardStatus + '&checkUserMobileStatus=' + that.data.activityInfo.checkUserMobileStatus + '&checkUserNameStatus=' + that.data.activityInfo.checkUserNameStatus + "&checkAreaStatus=" + 
        that.data.activityInfo.checkAreaStatus + "&addressInfoList=" + 
        JSON.stringify(that.data.activityInfo.addressInfoList) + "&cover=https://huibenbook.chaoxing.com/activity" + that.data.activityInfo.activityCover + "&uploadStatus=" + that.data.activityInfo.uploadStatus
      })
    }
  },

  /**
   * 报名
   */
  enroll: function(){
    var that = this;
    var userinfo = wx.getStorageSync('userInfo');
    console.log(userinfo.nickName);
    wx.request({
      url: app.globalData.activityHost + '/services/activityaction/joinActivity',
      data: {
        fid: app.globalData.fid,
        uid: wx.getStorageSync('cxid'),
        activityId: that.data.activityId,
        userName: userinfo.nickName,
        IDCard: "",
        userMobile: wx.getStorageSync('phone')
      },
      success: function (res) {
        console.log(res);
        if (res.data.result == "0") {
          wx.showModal({
            title: '报名成功',
            content: '点击确定按钮去上传作品',
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/zpsc/upload/upload?activityId=' + that.data.activityId,
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: '报名失败，请稍后再试',
            icon: 'none'
          })
        } 
      },
      fail: function () {
       wx.showToast({
         title: '报名失败，请稍后再试',
         icon: 'none'
       })
      }
    })
  },

  wycyActive:function(event){
    console.log(event);
    var that = this;
    //判断是否授权基本信息
    var cxid = wx.getStorageSync('cxid');
    if (cxid && cxid > 0) {
      // 判断是否已经报名
      if(that.data.signUpIng == 0){
        that.checkStatus();
      }else if(that.data.signUpIng == 1){
        wx.showToast({
          title: '活动已结束',
          icon: 'none',
          duration: 2000
        })
      }else if(that.data.signUpIng == 2){
        wx.showToast({
          title: '当前活动未开始',
          icon: 'none',
          duration: 2000
        })
      }
      
      //报名后直接跳转到上传页面

      //没报名的话自动报名并且弹窗提示

    } else {
      wx.showModal({
        title: '提示',
        content: '是否去登录？',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login',
            })
          } else if (res.cancel) {
            console.log("不做任何处理")
          }
        }
      })
    }
  },

  /**
   * 返回活动详情
   */
  gotoActivity: function(){
    wx.navigateBack({
      
    })
  },

  /**
   * 点赞
   */
  praiseFunc: function(e){
    console.log(e);
    var index = e.currentTarget.dataset.index;
    var type = e.currentTarget.dataset.type;
    console.log("左右： " + type);
    var that = this;
    var cxid = wx.getStorageSync('cxid');
    if(cxid && cxid > 0){
      wx.request({
        url: "https://huibenbook.chaoxing.com/activity/services/activityaction/addActivityGreat",
        data: {
          fid: app.globalData.fid,
          uid: wx.getStorageSync('cxid'),
          productionId: e.currentTarget.dataset.id
        },
        success: function(res){
          console.log(res);
          if(res.data.result == 0){
            //点赞成功
            console.log(res.data.msg);
            if(type == 1){
              //左边
              let list = [...that.data.leftList]; 
              that.data.leftList[index]['greatTotal'] = that.data.leftList[index]['greatTotal'] + 1;
              console.log("点赞更新后：" + that.data.leftList[index]['greatTotal']);
              that.setData({  
                leftList: list  
              })
              console.log("点赞更新后：" + that.data.leftList[index]['greatTotal']);
            }else{
              //右边
              let list = [...that.data.rightList]; 
              that.data.rightList[index]['greatTotal'] = that.data.rightList[index]['greatTotal'] +1;
              that.setData({  
                rightList: list  
              })
            }
          }else{
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
        },
        fail: function(){
          console.log("点赞异常");
        }
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '现在去登录吗？',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login',
            })
          } else if (res.cancel) {
            console.log("取消登录");
          }
        }
      })
    }
    
  },

  /**
   * 分享
   */
  share: function(e){
    console.log(e);
    var type = e.currentTarget.dataset.type;
    var activityId = e.currentTarget.dataset.id;
    var uid = wx.getStorageSync('cxid');
    //TODO 暂时不考虑用户登录问题
    var url = '/pages/link/link?url=https://videoshequ3.chaoxing.com/miniprogram/play&type=' + type + "&activityId=" + activityId + "&uid=" + uid + '&fid=' + app.globalData.fid + '&fidEnc=' + app.globalData.fidEnc;
    return {
      title: app.globalData.site.name,
      path: url
    }
  }



})